<?php

namespace Frieza\Modules\SpiderUser\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\model\Member;
use Doraemon\model\Spider\SpiderObjectMap as dbSpiderObjectMap;
use Doraemon\service\Spider\SpiderUserList;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;

class SpiderUserController extends Controller
{

    const PAGE_SIZE = 20;
    public function list(Request $request, Content $content)
    {
        $params = $request->all();
        $params['page'] = $request->input('page', 1);
        $params['per_page'] = $request->input('per_page', self::PAGE_SIZE);
        if(!isset($params['uid'])) {
            $request->merge(['uid'=>$params['uid']]);
        }

        return $content
            ->header('第三方用户管理')
            ->breadcrumb(
                [
                    'text' => '第三方用户列表',
                    'url'  => '/spiderUser/list'
                ]
            )
            ->body(self::listAction($params));
    }


    private static function listAction($params = [])
    {
        $data = dbSpiderObjectMap::getUserList($params);

        $list = $data['data'];
        if (!empty($list)) {
            foreach ($list as &$row) {
                $row['detail'] = SpiderUserList::getOtherMapList($row['detail']);
            }
        }

        $gridModel = new pGridDataModel($list, $data['total'], [
            'perPage' => $params['per_page'],
        ]);

        $listGrid = Admin::grid($gridModel, function (Grid $grid) {
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->expandFilter();
            $grid->paginate(self::PAGE_SIZE);

            // 筛选项
            $grid->filter(function (Grid\Filter $filter) {
                $filter->disableIdFilter();
                $filter->column(1 / 2, function ($filter) {
                    $filter->equal('uid', '用户ID')->placeholder('请输入用户ID');
                });
            });
            $grid->column('id');
            $grid->column('uid', '用户ID')->display(function () {
                return "<a href='". url("admin/spiderUser/note/list?uid=$this->obj_id") . "' target='_self'>".$this->obj_id."</a>";
            });
            $grid->column('nickName', '用户昵称')->display(function () {
               return  Member::getNickByUid($this->obj_id);
            });
            $grid->column('source', '来源')->display(function () {
                $sourceArr = array_column($this->detail, 'source');
                return implode('<br/>', $sourceArr);
            });
            $grid->column('otherId', '第三方用户ID')->display(function () {
                $otherIdArr = array_column($this->detail, 'otherId');
                return implode('<br/>', $otherIdArr);
            });
            $grid->column('addtime', '操作时间')->display(function () {
               return "创建时间：".$this->created_at->format('Y-m-d H:i:s')."<br/>最后自改时间".$this->updated_at->format('Y-m-d H:i:s');
            });

        });

        return $listGrid;
    }


    public function edit(Content $content, $id = 0)
    {
        $tab = new Tab();
        if ($id > 0) {
            $title = '第三方用户编辑';
        } else {
            $title = '创建第三方用户';
        }
        $tab->add("$title", $this->editAction($id));
        return $content
            ->header('第三方用户管理')
            ->breadcrumb(
                [
                    'text' => '第三方用户列表',
                    'url'  => '/spiderUser/list'
                ],
                ['text' => "$title"]
            )
            ->body($tab);
    }

    private function editAction($id = 0)
    {

        if ($id > 0) {
            $info = SpiderUserList::getInfoById($id);
            if (!empty($info)) {
                foreach ($info['detail'] as $source => $item) {
                    $info['source_' . $source] = $item['otherId'];
                }
            }
            $form = new Form($info);
            $form->hidden('id');
            $form->text('obj_id', '用户ID')->readonly();
        } else {
            $form = new Form();
            $form->text('obj_id', '用户ID')->required('不能为空');
        }
        foreach (SpiderUserList::SOURCE_MAP as $source => $sourceName) {
            $form->text('source_'.$source, $sourceName);
        }
        $form->action('/admin/spiderUser/list/save');

        return $form;
    }

    /**
     * 保存
     *
     * @param Request $request
     */
    public function saveSubmit(Request $request)
    {
        $params = $request->all();
        $id = $params['id'] ?? 0;
        $uid = $params['obj_id'] ?? '';
        if (empty($uid)) {
            $error = new MessageBag([
                'title' => '用户ID不能为空',
            ]);
            return back()->with(compact('error'));
        }
        if (!is_numeric($uid)) {
            $error = new MessageBag([
                'title' => '用户ID格式错误',
            ]);
            return back()->with(compact('error'));
        }

        // 判断用户ID是否重复
        $userInfo =  Member::getUser($uid);
        if (empty($userInfo)) {
            $error = new MessageBag([
                'title' => '用户ID不存在',
            ]);
            return back()->with(compact('error'));
        }
        $res = dbSpiderObjectMap::getInfoByUid($uid);
        if((empty($id) && !empty($res)) || (!empty($id) && $uid != $res['obj_id'])) {
            $error = new MessageBag([
                'title' => '用户ID重复',
            ]);
            return back()->with(compact('error'));
        }
        $detail = [];
        foreach (SpiderUserList::SOURCE_MAP as $source => $sourceName) {
            $_value = $params['source_' . $source] ?? '';
            if (!empty($_value)) {
                $detail[$source] = trim($_value);
            }
        }
        if (empty($detail)) {
            $error = new MessageBag([
                'title' => '第三方用户ID不能全为空',
            ]);
            return back()->with(compact('error'));
        }
        $detail = json_encode($detail, JSON_UNESCAPED_UNICODE);
        $updateFields = [
            'uid' => $uid,
            'detail' => $detail,
        ];

        try {
            if ($id > 0) {
                $result = dbSpiderObjectMap::saveUserData($updateFields, ['id' => $id]);
            } else {
                $result = dbSpiderObjectMap::saveUserData($updateFields);
            }
            if ($result) {
                return back()->with('success', new MessageBag([
                    'title' => '操作成功'
                ]));
            } else {
                return back()->with('error', new MessageBag([
                    'title' => '操作错误，请重试'
                ]));
            }
        } catch (\Exception $e) {
            return back()->with('error', new MessageBag([
                'title' => $e->getMessage()
            ]));
        }
    }

    /**
     * 删除
     * @param $id
     * @return void
     */
    public function del($id)
    {
        dbSpiderObjectMap::delById($id);
        return response()->json([
            'status'  => true,
            'message' => "操作成功",
        ]);
    }
}